package com.evil.Servlet;

import com.evil.Bean.LocationBean;
import com.evil.DAO.LocationDAO;
import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/********************************************
 * 工程名：Web
 * 包名：${PACKAGE_NAME}
 * 时间：16-9-19 下午8:48
 * 作者：白雨濃 evil
 * 邮箱：evilbai@foxmail.com
 * 内容：
 ********************************************/
public class LocationServlet extends BaseServlet
{
    private String phone;
    private String imei;
    private String phoneManufacturer, phoneModel;/*手机厂商，手机型号*/
    private String androidVersion;/*android版本*/
    private String address;
    private int mcc, mnc, lac, cell;

    private String ip;
    private String info;

    private LocationBean bean;

    private static Logger log = Logger.getLogger(LocationServlet.class);

    @Override
    public void doPost() throws IOException
    {
        phone = getParameter("phone");
        imei = getParameter("imei");
        phoneManufacturer = getParameter("phoneManufacturer");
        phoneModel = getParameter("phoneModel");
        androidVersion = getParameter("androidVersion");
        address = getParameter("address");
        mcc = getParameterInt("mcc");
        mnc = getParameterInt("mnc");
        lac = getParameterInt("lac");
        cell = getParameterInt("cell");

        ip = getIpAddr(request);

        bean = new LocationBean(phoneManufacturer,
                phoneModel,
                androidVersion,
                ip,
                mcc,
                mnc,
                lac,
                cell,
                address,
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                        .format(new Date()));

        log.info("用户：" + phone + "登录\r\n>>>详情：" + bean.toString()+"\r\n");

        insertLocation();
    }

    /**
     * 地址更新
     */
    private void insertLocation()
    {
        new LocationDAO().insertLocation(phone, bean);
    }


    /**
     * 获取访问至ip
     *
     * @param request
     * @return
     */
    public String getIpAddr(HttpServletRequest request)
    {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
